import { NextApiResponse } from "next";
import { AuthenticatedRequest, withAuth } from "@/common/middleware/auth";
import R from "@common/type/response";
import { SysMenuService } from "@common/service/sys_menu";

function buildRouterTree(list: any[]) {
  const map: Record<number, any> = {};
  const roots: any[] = [];
  list.forEach(item => {
    let menu: any = {
      name: item.path,
      list: item.path,
      meta: {
        label: item.menu_name,
        icon: item.icon,
      },
    }
    if (item.menu_type === 'C') {
      menu.list = item.path;
      menu['create'] = item.path + '/create';
      menu['edit'] = item.path + '/edit/:id';
      menu['show'] = item.path + '/show/:id';
    }
    if (item.menu_type === 'M' || item.menu_type === 'C') {
      if (item.parent_id && map[item.parent_id]) {
        let parent = map[item.parent_id];
        menu.name = parent.name + '/' + item.path;
        menu.list = parent.list + '/' + item.path;
        menu.create = parent.list + '/' + item.path + '/create';
        menu.edit = parent.list + '/' + item.path + '/edit/:id';
        menu.show = parent.list + '/' + item.path + '/show/:id';
        menu.meta.parent = parent.name;
      }
      roots.push(menu);
    }
    map[item.menu_id] = { 
      ...menu
    };
  });
  // list.forEach(item => {
  //   if (item.menu_type === 'M' || item.menu_type === 'C') {
  //     if (item.parent_id && map[item.parent_id]) {
  //       map[item.parent_id].children.push(map[item.menu_id]);
  //     } else {
  //       roots.push(map[item.menu_id]);
  //     }
  //   }
  // });
  return roots;
}

export async function getRouters(req: AuthenticatedRequest, res: NextApiResponse) {
  const loginUser = req.user;
  if (!loginUser) {
    return R.unauthorized(res, "unauthorized");
  }
  let routers = []
  if(loginUser.userId === 1){
    routers = await SysMenuService.list();
  }else{
    routers = await SysMenuService.listByUserId(loginUser.userId);
  }
  const routerTree = buildRouterTree(routers);
  return R.success(res, routerTree);
}


export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    getRouters(req, res);
  } else {
    res.status(405).json({ success: false, message: 'Method Not Allowed' });
  }
}

export default withAuth(handler); 